<template>
  <div class="user-login">
    <el-row type="flex" justify="center" align="middle" class="login-con">
      <el-row type="flex" justify="space-between" class="con">
        <el-row class="con-img">
          <img src="@/assets/Bitmap.png" />
        </el-row>
        <el-row class="con-form">
          <el-row class="form-title">
            <el-row type="flex" justify="center">
              <img src="@/assets/logo.png" />
              <span class="font1">能源区块链交易系统</span>
            </el-row>
            <p v-if="status == 'reg'" class="font2">账号注册</p>
            <p
              style="margin: 10px 0"
              v-else-if="status == 'login'"
              class="font2"
            >
              登录
            </p>
          </el-row>
          <el-row
            class="form-container"
            type="flex"
            justify="center"
            align="middle"
          >
            <!-- <div class="form-title">
              <el-row type="flex" justify="center" align="middle">
                <img src="@/assets/logo.png" />
                <span class="font1">能源区块链交易系统</span>
              </el-row>
              <p v-if="status == 'reg'" class="font2">账号注册</p>
              <p
                style="margin: 10px 0"
                v-else-if="status == 'login'"
                class="font2"
              >
                登录
              </p>
            </div> -->
            <el-form
              ref="form"
              :model="user"
              :rules="rules"
              label-width="0"
              @keyup.enter.native="submitBtn"
              style="width: 100%"
            >
              <el-form-item prop="org_name" v-if="status == 'reg'">
                <el-input
                  ref="user"
                  type="text"
                  placeholder="请输入机构名称"
                  v-model="user.org_name"
                ></el-input>
              </el-form-item>

              <el-form-item v-if="status == 'reg'" prop="type">
                <el-row type="flex" justify="space-between" class="nest">
                  <!-- <el-col :span="18"
                    ><el-input
                      placeholder="请输入内容"
                      v-model="user.role"
                      class="input-with-select"
                    >
                    </el-input
                  ></el-col>
                  <el-col :span="9">-->

                  <el-select
                    v-model="user.type"
                    clearable
                    placeholder="请选择机构角色"
                    style="width: 100%"
                  >
                    <el-option
                      v-for="item in options"
                      :key="item.value"
                      :label="item.name"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                  <!-- </el-col> -->
                </el-row>
              </el-form-item>
              <el-form-item
                prop="phone"
                :rules="[{ validator: phoneRuler, required: true }]"
              >
                <el-input
                  ref="user"
                  type="text"
                  placeholder="请输入手机号"
                  v-model="user.phone"
                ></el-input>
              </el-form-item>
              <el-form-item
                prop="email"
                :rules="[{ validator: emailRuler }]"
                v-if="status == 'reg'"
              >
                <el-input
                  type="text"
                  placeholder="请输入邮箱（可选）"
                  v-model="user.email"
                ></el-input>
              </el-form-item>
              <!-- <el-form-item
                v-if="status == 'reg'"
                prop="code"
                :rules="[{ validator: code, required: true }]"
              >-->
              <el-form-item v-if="status == 'reg'" prop="smscode">
                <el-input
                  type="text"
                  placeholder="请输入验证码"
                  v-model="user.smscode"
                >
                  <el-button
                    slot="append"
                    @click="sendCode"
                    :disabled="isNotBtn"
                    >{{ txt }}</el-button
                  >
                  <!-- <button type="button" onclick="fn()">获取验证码</button> -->
                </el-input>
              </el-form-item>

              <el-form-item prop="passwd">
                <el-input
                  type="password"
                  placeholder="请输入密码"
                  v-model="user.passwd"
                ></el-input>
              </el-form-item>
              <el-row
                type="flex"
                justify="space-between"
                v-if="status == 'login'"
              >
                <el-row>
                  <el-button type="text">忘记密码？</el-button>
                </el-row>
                <el-row>
                  <span>没有账号？去</span>
                  <el-button @click="handleReg" type="text">注册</el-button>
                </el-row>
              </el-row>
              <el-row type="flex" justify="center" v-if="status == 'login'">
                <el-button
                  type="primary"
                  class="submit-btn"
                  size="small"
                  @click="submitBtn"
                  :loading="loading"
                  >确认登录</el-button
                >
              </el-row>
              <el-row type="flex" justify="center" v-else-if="status == 'reg'">
                <el-button
                  type="primary"
                  class="submit-btn"
                  size="small"
                  @click="Reg"
                  :loading="loading"
                  >注册</el-button
                >
              </el-row>
            </el-form>
          </el-row>
        </el-row>
      </el-row>
    </el-row>
    <el-dialog
      :title="dlgTitle"
      :visible.sync="dlgVib"
      @closed="closeDlg"
      append-to-body
      :width="width"
    >
      <el-row class="tip" type="flex" justify="center"
        >恭喜注册成功，账户需经电网组织审核通过后方可在平台登录和交易，谢谢您的配合。</el-row
      >
      <el-row type="flex" justify="center" class="notice">
        <el-button @click="handleNotice" type="primary" plain size="small"
          >我知道了</el-button
        >
      </el-row>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import Vue from "vue";
import Component from "vue-class-component";
import Constant from "@/lib/Constant";
import Route from "vue-router";

// const backgroundImage = require("@/assets/bg.png");

@Component
export default class Login extends Vue {
  public name: string = "UserLogin";
  protected status: string = "login";
  // for diog
  protected dlgVib: boolean = false;
  protected dlgTitle: string = "";
  protected dlgCpt: any = null;
  protected width: any = "";
  protected modules: any = null;
  protected homeUrl: string = "";
  protected loading: boolean = false;
  // protected backgroundImage: string = backgroundImage;
  protected user: any = {
    // username: "",
    // password: "",
    // smscode:
  };
  protected rules: any = {
    org_name: [
      { required: true, message: "请输入机构名称", trigger: "change" },
    ],
    type: [{ required: true, message: "请选择机构角色", trigger: "change" }],
    smscode: [{ required: true, message: "请输入验证码", trigger: "change" }],
    passwd: [{ required: true, message: "请输入密码", trigger: "change" }],
  };
  protected userInfor: any = {};
  protected checked: boolean = false;
  protected options: any = [
    { name: "购电方", value: "consumer" },
    { name: "产销者", value: "prosumer" }
    // { name: "电网机构", value: "grid" },
  ];
  protected select: any = 1;
  private seconds: number = 59;
  private speed: number = 1000;
  private txt: string = "发送验证码";
  private isNotBtn: boolean = false;

  protected async created(): Promise<void> {
    this.$nextTick(() => {
      const getUserFocus: any = this.$refs.user;
      getUserFocus.focus();
    });
  }

  // 校验用户名为手机号
  protected phoneRuler: any = (rule: any, value: any, callback: any) => {
    if (value === "") {
      callback(new Error("请输入用户名（手机号）"));
    } else if (!/^1[3456789]\d{9}$/.test(value)) {
      callback(new Error("请输入正确的手机号"));
    } else {
      callback();
    }
  }
  protected emailRuler: any = (rule: any, value: any, callback: any) => {
    if (!value) {
      callback();
    } else if (
      !/^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/.test(
        value
      )
    ) {
      callback(new Error("请输入正确的邮箱"));
    } else {
      callback();
    }
  }

  protected submitBtn() {
    (this.$refs.form as any).validate(async (valid: boolean) => {
      if (valid) {
        this.loading = true;
        const params = {
          phone: this.user.phone,
          passwd: this.user.passwd,
        };

        try {
          const res: any = await this.$api.Login(params);
          const { user, token } = res.data;
          localStorage.setItem("accessToken", token);
          localStorage.setItem("userInfo", JSON.stringify(user));
          // const userInfo: any = await this.$api.getAaccounts();

          const redirect: any = this.$route.query.redirect;

          if (redirect) {
            this.$router.push({ path: redirect });
          } else {
            this.$router.push({ path: "/trading", name: "交易大厅" });
          }
        } catch (e) {
        } finally {
          this.loading = false;
        }
      }
    });
  }

  // 注册
  protected handleReg() {
    this.$set(this, "status", "reg");
  }

  protected Reg() {
    (this.$refs.form as any).validate(async (valid: boolean) => {
      if (valid) {
        this.loading = true;

        try {
          const res: any = await this.$api.regin(this.user);
          this.dlgVib = true;
          this.width = "20%";
        } catch (e) {
          this.$message.error(Vue.prototype.$errorMessage);
        } finally {
          this.loading = false;
        }
      }
    });
  }
  protected handleNotice() {
    this.dlgVib = false;
    this.status = "login";
  }

  private sendCode() {
    let time: any = 60;
    let timer: any = null;
    this.txt = time + "秒后重新发送";
    this.isNotBtn = true;
    timer = setInterval(() => {
      // 定时器到底了 兄弟们回家啦
      if (time === 1) {
        clearInterval(timer);
        this.txt = "发送验证码";
        this.isNotBtn = false;
      } else {
        time--;
        this.txt = time + "秒后重新发送";
      }
    }, 1000);
  }
}
</script>

<style lang="scss" scoped>
.user-login {
  position: relative;
  overflow: hidden;
  background: url("../assets/bg.png") no-repeat;
  background-size: 100% 100%;
  height: 100%;
  width: 100%;
  .login-con {
    position: absolute;
    top: 0px;
    left: 0;
    right: 0;
    bottom: 0px;

    .con {
      display: flex;
      justify-content: center;
      align-items: center;
      .con-img {
        display: flex;
        justify-content: center;
        align-items: center;
        img {
          width: auto;
          // height: 700px;
          height: 89vh;
          // width: 670px;
          overflow: hidden;
        }
      }
      .con-form {
        // height: 667px;
        height: 85vh;
        width: 398px;
        overflow: hidden;
        background-color: #fff;
        border-radius: 6px;
        box-shadow: 1px 1px 2px #eee;
        margin-left: -20px;
        padding: 0 40px;
        .form-title {
          margin-top: 40px;
          text-align: center;
          .font1 {
            font-size: 24px;
            color: #077be8;
          }
          .font2 {
            font-size: 24px;
            color: #333333;
          }
        }

        .form-container {
          // display: flex;
          // justify-content: center;
          // flex-direction: column;
          height: 68%;
          .form-title {
            text-align: center;
            .font1 {
              font-size: 24px;
              color: #077be8;
            }
            .font2 {
              font-size: 24px;
              color: #333333;
            }
          }
          /deep/ .el-input__inner {
            border-top: none;
            border-left: none;
            border-right: none;

            border-radius: 0;
          }
          /deep/ .el-form-item {
            margin-bottom: 16px;
          }
          .nest {
            border-bottom: 1px solid #ccc;
            /deep/ .el-input__inner {
              border-bottom: none;
            }
          }
          .submit-btn {
            margin-bottom: 25px;
            width: 100%;
          }
        }
      }
    }
  }
}
.tip {
  text-align: center;
}
.notice {
  margin-top: 20px;
}
</style>



